﻿$().ready(function () {
    $("#optPathologyDetail").attr("class", "ListSelectedOption");
    $("#breadcrumb").append('<li><a href="' + $("#urlPathologyDetail").val() + '" title="Detalle de la Patología">Detalle de la Patología</a></li>');

	///Toolbar
	$('#btnClear').live('click', function () {
		ClearForm();
	});

	$('#btnNew').live('click', function () {
		if (confirm('¿Desea abandonar la edición y crear un registro nuevo?')) {
		    window.location = $('#urlCreate').val();
		}
	});

	///Menu
	$('#menuClear').live('click', function () {
		ClearForm();
	});

	$('#menuNew').live('click', function () {
		if (confirm('¿Desea abandonar la edición y crear un registro nuevo?')) {
		    window.location = $('#urlCreate').val();
		}
	});

	$('#btnSearch').click(function () {
	    Search();
	});

	$("#txtStartDate").datepicker({
	    buttonImageOnly: true,
	    changeMonth: true,
	    changeYear: true
	});

	$("#txtEndDate").datepicker({
	    buttonImageOnly: true,
	    changeMonth: true,
	    changeYear: true
	});

	if (!(typeof $('#txtPersonFilter')[0] === "undefined")) {
	    InitAutocomplete();
	}
});

function ConfirmDelete(id) {
	if (confirm('¿Esta seguro que desea eliminar, Detalle Patología?')) {
		Delete(id);
	}
}

function Delete(objectId) {
	$.ajax(
    {
    	type: "POST",
    	url: $('#urlDelete').val(),
    	data:
            JSON.stringify({
            	id: objectId
            }),

    	contentType: 'application/json; charset=utf-8',
    	dataType: 'json',
    	success: function (result) {
    		if (result.success) {
    		    window.location = "/ODSYSUI/PathologyDetail/SetMessage?id=1";
    		}
    		else {
    			$("#lblErrorText").text(result.msg);
    			$("#lblError").show(300).delay(5000).hide(400);
    		}
    	},
    	error: function (req, status, error) {
    	    window.location = "/ODSYSUI/PathologyDetail/SetMessage?id=2";
    	}
    });
}

function ClearForm() {
	//Limpia combos
	var cmbPatologia = $('#cmbPatologia');
	if (cmbPatologia.length > 0) {
		cmbPatologia[0].selectedIndex = 0;
	}

	//Limpia los textbox
	$('#txtID').val('');
	$('#txtName').val('');

	//Remueve todos los mensajes de error que genera el framework
	$('.field-validation-error').remove();
	$(":input").removeClass("input-validation-error");
}

function InitAutocomplete() {
    $("#txtPersonFilter").autocomplete({
        source: function (request, response) {
            $.ajax({
                type: "POST",
                url: $('#urlGetPatients').val(),
                dataType: "json",
                data: {
                    searchString: request.term,
                    IsByName: $('#rdbNameFilter').is(':checked'),
                    maxRows: 12
                },
                parse: function (data) {
                    var rows = new Array();
                    for (var i = 0; i < data.length; i++) {
                        rows[i] = { data: data[i], value: data[i].name, result: data[i].name };
                    }
                    return rows;
                },
                success: function (data) {
                    response($.map(data, function (item) {
                        return {
                            label: item.name + " " + item.firstName + " " + item.lastName + ". ID: " + item.identification,
                            ID: item.personID,
                            Name: item.name,
                            FirstName: item.firstName,
                            LastName: item.lastName,
                            Identification: item.identification,
                            DefaultPhone: item.defaultPhone
                        }
                    }));
                },
                error: function (data, status, e) {
                    debugger;
                    alert(e);
                }
            });
        },
        minLength: 0,
        select: function (event, ui) {
            $('#personID').val(ui.item.ID);
        }
    });

    $("#txtPersonFilter").keyup(function () {
        if (!this.value) {
            $('#personID').val();
        }
    });
}

function Search() {
    var startDate = $('#txtStartDate').val();
    var endDate = $('#txtEndDate').val();
    var date1 = null;
    var date2 = null;

    if (startDate != "") {
        var d1 = parseInt(startDate.substring(0, 2));
        var m1 = parseInt(startDate.substring(3, 5)) - 1;
        var y1 = parseInt(startDate.substring(6, 10));
        date1 = new Date(y1, m1, d1);
    }

    if (endDate != "") {
        var d1 = parseInt(endDate.substring(0, 2));
        var m1 = parseInt(endDate.substring(3, 5)) - 1;
        var y1 = parseInt(endDate.substring(6, 10));
        date2 = new Date(y1, m1, d1);
    }

    $.ajax(
    {
        type: "POST",
        traditional: true,
        url: $("#urlSearch").val(),
        secureuri: false,
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        enctype: 'multipart/form-data',
        data:
            JSON.stringify({
                pathologyID: $('#cmbpathologyID').val(),
                name: $('#txtName').val(),
                startDate: date1,
                endDate: date2,
            }),

        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (result) {
            if (result.success) {
                window.location = $("#urlSearch").val();
            }
            else {
                $("#lblErrorText").text(result.msg);
                $("#lblError").show(300).delay(5000).hide(400);
            }
        },
        error: function (req, status, error) {
            debugger;
            //window.location = "/ODSYSUI/RemovablePartialProsthesisDesign/SetMessage?id=2";
        }
    });
}